#include "jrsc.h"

// 内存写入回调函数
size_t write_callback(void *ptr, size_t size, size_t nmemb, void *userdata) {
    size_t realsize = size * nmemb;
    FILE *memstream = (FILE *)userdata;
    fwrite(ptr, size, nmemb, memstream);
    return realsize;
}

// 打印推荐的古诗词
void print_recommended_poetry(const char *response, size_t size) {
    cJSON *json = cJSON_ParseWithLength(response, size);
    if (json == NULL) {
        fprintf(stderr, "解析 JSON 失败: [%s]\n", cJSON_GetErrorPtr());
        return;
    }

    cJSON *data = cJSON_GetObjectItemCaseSensitive(json, "data");
    if (!cJSON_IsObject(data)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'data' 对象\n");
        cJSON_Delete(json);
        return;
    }

    cJSON *content = cJSON_GetObjectItemCaseSensitive(data, "content");
    if (!cJSON_IsString(content) || (content->valuestring == NULL)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'content' 字符串\n");
        cJSON_Delete(json);
        return;
    }

    printf("今日推荐古诗：%s\n", content->valuestring);
    cJSON_Delete(json);
}

// 获取并打印推荐的古诗词
void get_and_print_poetry(void) {
    CURL *client;
    CURLcode err;
    char *response;
    size_t size;

    FILE *memstream = open_memstream(&response, &size);
    if (memstream == NULL) {
        perror("open_memstream");
        return;
    }

    curl_global_init(CURL_GLOBAL_ALL);
    client = curl_easy_init();

    curl_easy_setopt(client, CURLOPT_URL, "https://v2.jinrishici.com/sentence");
    curl_easy_setopt(client, CURLOPT_WRITEDATA, memstream);
    curl_easy_setopt(client, CURLOPT_WRITEFUNCTION, write_callback);

    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "X-User-Token: o9M10gtneoIxRLk5UO13fUG7guYxnS7h"); // 替换 YOUR_API_KEY 为你的 API Key
    curl_easy_setopt(client, CURLOPT_HTTPHEADER, headers);

    err = curl_easy_perform(client);
    fclose(memstream);

    if (err != CURLE_OK) {
        fprintf(stderr, "curl_easy_perform() 失败: %s\n", curl_easy_strerror(err));
    } else {
        print_recommended_poetry(response, size);
    }

    curl_slist_free_all(headers);
    curl_easy_cleanup(client);
    free(response);
    curl_global_cleanup();
}
